import { CanActivate, ExecutionContext, HttpException, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Roles } from "./roles.decorator";
import { AuthRepositry } from '../auth.repositry'

/**
 * 数据操作权限守卫
 */
@Injectable()
export class DataHandle implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private authRepositry: AuthRepositry
  ) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {

    // 获取权限code
    const handleCode = this.reflector.get(Roles, context.getHandler())
    // 获取用户角色Ids
    const roleIds = context.switchToHttp().getRequest()['user']['roleIds'] ?? []

    // 查询是否有权限
    const isPermission = await this.authRepositry.getHandlePermission(handleCode, roleIds)

    if (isPermission) {
      return true
    } else {
      throw new HttpException({
        code: 500,
        meaasge: '无权限操作'
      }, 500)
    }
  }
}